import type { PermissionTreeNode } from '@/DatabaseType/User';
import type { DataNode } from 'antd/lib/tree';

export type MergeDataNode = PermissionTreeNode &
  Pick<DataNode, 'key' | 'title'> & {
    children?: MergeDataNode[];
  };

export function formatPermissionTreeToTreeFC(
  permissionTree: PermissionTreeNode[],
): MergeDataNode[] {
  return permissionTree.map((permissionTreeNode) => ({
    ...permissionTreeNode,
    key: permissionTreeNode.id,
    title: permissionTreeNode.znName,
    children: formatPermissionTreeToTreeFC(permissionTreeNode.children || []),
  }));
}

// 获取权限树的所有叶子节点
export function flatTreeLeaves(
  permissionTree: PermissionTreeNode[],
  leaves = [] as PermissionTreeNode[],
  halfLeaves = [] as PermissionTreeNode[],
) {
  permissionTree.forEach((permissionTreeNode) => {
    const { children, funcType } = permissionTreeNode;
    // 如果是按钮，或者是菜单但是没有子集权限
    if (funcType === '2' || !children?.length) {
      leaves.push(permissionTreeNode);
    } else {
      halfLeaves.push(permissionTreeNode);
      flatTreeLeaves(children, leaves, halfLeaves);
    }
  });
  return { leaves, halfLeaves };
}
